/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.extend.mapping;

import cn.hutool.core.util.StrUtil;
import cn.star.framework.extend.core.Column;
import cn.star.framework.extend.core.Database;
import cn.star.framework.extend.core.Table;
import cn.star.framework.extend.core.Table.GeneratorTableConfiguration;
import org.hibernate.dialect.Dialect;

/**
 * ColumnInfo<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public class ColumnInfo extends org.hibernate.mapping.Column {

  public ColumnInfo(
      Column column, Table table, Database database, GeneratorTableConfiguration config) {
    this.setName(getColumnName(column, config.isQuoted()));
    this.setUnique(column.isUnique());
    this.setNullable(column.isNullable());

    this.setSqlType(column.getSqlType(database.getDialect(), database.getMetadata()));
    this.setSqlTypeCode(column.getSqlTypeCode());

    this.setLength(column.getLength());
    this.setPrecision(column.getPrecision());
    this.setScale(column.getScale());

    this.setTypeIndex(column.getOrder());

    this.setComment(column.getComment());
    String defaultValue = column.getDefaultValue();
    if (StrUtil.isNotBlank(defaultValue)) {
      // 生成Sql中，需要将默认值使用 '' 来包裹
      this.setDefaultValue(StrUtil.format("'{}'", defaultValue));
    }

    this.setCheckConstraint(column.getCheckConstraint());
    this.setCustomRead(column.getCustomRead());
    this.setCustomWrite(column.getCustomWrite());
  }

  private String getColumnName(Column column, boolean quoted) {
    String name = column.getName();
    if (Dialect.QUOTE.indexOf(name.charAt(0)) < 0 && quoted) {
      name = StrUtil.format("[{}]", name);
    }

    return name;
  }
}
